package com.suny.sf_server.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suny.constant.RedisKeyConstant;
import com.suny.result.ResponseCode;
import com.suny.sf_server.redis.IRedisService;
import com.suny.sf_server.service.FenceService;
import com.suny.sf_server.service.PenService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.suny.FarmStocks.domain.FarmStocks;
import com.suny.FarmStocks.dto.FarmStocksAddDTO;
import com.suny.FarmStocks.dto.FarmStocksQueryDTO;
import com.suny.FarmStocks.vo.FarmStocksVO;
import com.suny.sf_server.mapper.FarmStocksMapper;
import com.suny.sf_server.service.FarmStocksService;
import com.suny.sf_server.service.FarmService;
import com.suny.Farm.domain.Farm;
import com.suny.exception.BusinessException;
import com.suny.result.PageDTO;
import com.suny.Pen.domain.Pen;
import com.suny.Fence.domain.Fence;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FarmStocksServiceImpl extends ServiceImpl<FarmStocksMapper, FarmStocks>
    implements FarmStocksService {
    
    @Resource
    private FarmService farmService;
    
    @Resource
    private PenService penService;
    
    @Resource
    private FenceService fenceService;
    
    @Resource
    private IRedisService redisService;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(FarmStocksAddDTO dto) {
        // 验证牧场是否存在且启用
        Farm farm = farmService.getById(dto.getFarmId());
        if (farm == null || farm.getStatus() != 1) {
            throw new BusinessException("牧场不存在或未启用");
        }
        
        // 验证圈舍是否存在且启用
        Pen pen = penService.getById(dto.getPenId());
        if (pen == null || pen.getStatus() != 1) {
            throw new BusinessException("圈舍不存在或未启用");
        }
        
        // 验证围栏是否存在且启用
        Fence fence = fenceService.getById(dto.getFenceId());
        if (fence == null || fence.getStatus() != 1) {
            throw new BusinessException("围栏不存在或未启用");
        }
        
        // 保存存栏信息
        FarmStocks farmStocks = new FarmStocks();
        farmStocks.setFarmId(dto.getFarmId());
        farmStocks.setPenId(dto.getPenId());
        farmStocks.setFenceId(dto.getFenceId());
        farmStocks.setLivestockCount(dto.getLivestockCount());
        farmStocks.setStatus(1); // 设置为在栏
        farmStocks.setCreatedTime(new Date());
        farmStocks.setUpdatedTime(new Date());
        
        save(farmStocks);
        
        // 更新相关数量
        updateRelatedAmount(dto.getFarmId(), dto.getPenId(), dto.getFenceId(), dto.getLivestockCount());
        
        // 清除缓存
        clearCache(dto.getFarmId(), dto.getPenId(), dto.getFenceId());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void outStock(Integer id) {
        FarmStocks farmStocks = getById(id);
        if (farmStocks == null) {
            throw new BusinessException("存栏信息不存在");
        }
        
        if (farmStocks.getStatus() == 0) {
            throw new BusinessException("该批次已出栏");
        }
        
        // 更新出栏信息
        farmStocks.setStatus(0);
        farmStocks.setUpdatedTime(new Date());
        updateById(farmStocks);
        
        // 更新相关数量
        updateRelatedAmount(farmStocks.getFarmId(), farmStocks.getPenId(), 
                farmStocks.getFenceId(), -farmStocks.getLivestockCount());
        
        // 清除缓存
        clearCache(farmStocks.getFarmId(), farmStocks.getPenId(), farmStocks.getFenceId());
    }
    
    @Override
    public Page<FarmStocksVO> getList(PageDTO pageDTO) {
        // 1. 参数校验
        if (pageDTO == null || pageDTO.getPageNumber() <= 0 || pageDTO.getPageSize() <= 0) {
            throw new BusinessException(ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
        
        // 2. 生成包含分页参数的缓存key
        String cacheKey = String.format("%s:%d:%d", 
            RedisKeyConstant.FARM_STOCKS_LIST,
            pageDTO.getPageNumber(),
            pageDTO.getPageSize());
        
        // 3. 尝试从缓存获取
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }
        
        // 4. 查询数据库
        Page<FarmStocks> page = new Page<>(pageDTO.getPageNumber(), pageDTO.getPageSize());
        IPage<FarmStocksVO> voPage = baseMapper.selectFarmStocksVOPage(page);
        
        // 5. 处理空结果缓存
        if (voPage != null && voPage.getTotal() > 0) {
            redisService.setValue(cacheKey, voPage, RedisKeyConstant.CACHE_TIME);
        } else {
            redisService.setValue(cacheKey, voPage, RedisKeyConstant.EMPTY_CACHE_TIME);
        }
        
        return (Page<FarmStocksVO>) voPage;
    }
    
    @Override
    public Page<FarmStocksVO> getListByCondition(FarmStocksQueryDTO query) {
        // 1. 参数校验
        if (query == null || query.getPageSize() == null || query.getPageNumber() == null) {
            throw new BusinessException(ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
        
        // 2. 生成包含查询条件的缓存key
        String cacheKey = String.format("%s:%s:%d:%d", 
            RedisKeyConstant.FARM_STOCKS_LIST,
            query.hashCode(),
            query.getPageNumber(),
            query.getPageSize());
        
        // 3. 尝试从缓存获取
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }
        
        // 4. 查询数据库
        Page<FarmStocks> page = new Page<>(query.getPageNumber(), query.getPageSize());
        IPage<FarmStocksVO> voPage = baseMapper.selectFarmStocksVOPageByCondition(page, query);
        
        // 5. 处理空结果缓存
        if (voPage != null && voPage.getTotal() > 0) {
            redisService.setValue(cacheKey, voPage, RedisKeyConstant.CACHE_TIME);
        } else {
            redisService.setValue(cacheKey, voPage, RedisKeyConstant.EMPTY_CACHE_TIME);
        }
        
        return (Page<FarmStocksVO>) voPage;
    }
    
    @Override
    public List<FarmStocksVO> getListByFarmId(Integer farmId) {
        // 1. 参数校验
        if (farmId == null || farmId <= 0) {
            throw new BusinessException("无效的牧场ID");
        }
        
        // 2. 验证牧场是否存在
        Farm farm = farmService.getById(farmId);
        if (farm == null) {
            throw new BusinessException("牧场不存在");
        }
        
        // 3. 尝试从缓存获取
        String cacheKey = RedisKeyConstant.FARM_STOCKS_FARM_PREFIX + farmId;
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }
        
        // 4. 查询数据库
        List<FarmStocksVO> list = baseMapper.selectByFarmId(farmId);
        
        // 5. 处理空结果缓存
        if (list != null && !list.isEmpty()) {
            // 有数据才缓存
            redisService.setValue(cacheKey, list, RedisKeyConstant.CACHE_TIME);
        } else {
            // 空结果使用较短的缓存时间
            redisService.setValue(cacheKey, list, 5 * 60 * 1000); // 5分钟
        }
        
        return list;
    }
    // 统计牧场存栏量
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer countFarmLivestock(Integer farmId) {
        // 1. 参数校验
        if (farmId == null || farmId <= 0) {
            throw new BusinessException("无效的牧场ID");
        }
        
        // 2. 验证牧场是否存在
        Farm farm = farmService.getById(farmId);
        if (farm == null) {
            throw new BusinessException("牧场不存在");
        }
        
        String cacheKey = RedisKeyConstant.FARM_STOCKS_FARM_PREFIX + farmId + ":count";
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }
        
        Integer count = baseMapper.countFarmLivestock(farmId);
        
        // 3. 统计结果为0时使用较短的缓存时间
        if (count > 0) {
            redisService.setValue(cacheKey, count, RedisKeyConstant.CACHE_TIME);
        } else {
            redisService.setValue(cacheKey, count, 5 * 60 * 1000); // 5分钟
        }
        
        return count;
    }
    // 更新圈舍存栏量
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer countPenLivestock(Integer penId) {
        String cacheKey = RedisKeyConstant.FARM_STOCKS_PEN_PREFIX + penId + ":count";
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }
        
        Integer count = baseMapper.countPenLivestock(penId);
        
        redisService.setValue(cacheKey, count, RedisKeyConstant.CACHE_TIME);
        return count;
    }
    // 更新围栏存栏量
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer countFenceLivestock(Integer fenceId) {
        String cacheKey = RedisKeyConstant.FARM_STOCKS_FENCE_PREFIX + fenceId + ":count";
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }
        
        Integer count = baseMapper.countFenceLivestock(fenceId);
        
        redisService.setValue(cacheKey, count, RedisKeyConstant.CACHE_TIME);
        return count;
    }
    
    /**
     * 更新牧场、圈舍、围栏的存栏数量
     */
    private void updateRelatedAmount(Integer farmId, Integer penId, Integer fenceId, Integer amount) {
        // 更新牧场存栏量
        Farm farm = farmService.getById(farmId);
        farm.setAmountLivestock(farm.getAmountLivestock() + amount);
        farmService.updateById(farm);
        
        // 更新圈舍存栏量
        Pen pen = penService.getById(penId);
        pen.setAmountLivestock(pen.getAmountLivestock() + amount);
        penService.updateById(pen);
        
        // 更新围栏存栏量
        Fence fence = fenceService.getById(fenceId);
        fence.setAmountLivestock(fence.getAmountLivestock() + amount);
        fenceService.updateById(fence);
    }
    
    /**
     * 清除相关缓存
     */
    private void clearCache(Integer farmId, Integer penId, Integer fenceId) {
        // 清除存栏相关缓存 - 使用模式匹配删除所有分页缓存
        redisService.removePattern(RedisKeyConstant.FARM_STOCKS_LIST + ":*");
        redisService.remove(RedisKeyConstant.FARM_STOCKS_FARM_PREFIX + farmId);
        redisService.remove(RedisKeyConstant.FARM_STOCKS_FARM_PREFIX + farmId + ":count");
        redisService.remove(RedisKeyConstant.FARM_STOCKS_PEN_PREFIX + penId + ":count");
        redisService.remove(RedisKeyConstant.FARM_STOCKS_FENCE_PREFIX + fenceId + ":count");
        
        // 清除牧场相关缓存
        redisService.remove(RedisKeyConstant.FARM_LIST);
        redisService.remove(RedisKeyConstant.FARM_ENABLE_LIST);
        redisService.remove(RedisKeyConstant.FARM_DETAIL_PREFIX + farmId);
        redisService.remove(RedisKeyConstant.FARM_SELECT);
        
        // 清除圈舍相关缓存
        redisService.remove(RedisKeyConstant.PEN_LIST);
        redisService.remove(RedisKeyConstant.PEN_FARM_PREFIX + farmId);
        redisService.remove(RedisKeyConstant.PEN_FARM_PREFIX_SELECT + farmId);
        
        // 清除围栏相关缓存
        redisService.remove(RedisKeyConstant.FENCE_LIST);
        redisService.remove(RedisKeyConstant.FENCE_PEN_PREFIX + penId);
    }
}




